package ar.edu.itba.pod.Legajo47342.communication.handlers;

import ar.edu.itba.pod.Legajo47342.Node;
import ar.edu.itba.pod.Legajo47342.market.MarketImpl;
import ar.edu.itba.pod.simul.communication.Message;
import ar.edu.itba.pod.simul.communication.payload.ResourceTransferMessagePayload;
import ar.edu.itba.pod.simul.market.Resource;
import ar.edu.itba.pod.simul.market.ResourceStock;

import com.google.common.collect.Multiset;

public class ResourceTransferMessageHandler implements Handler {
	
	private Node node;

	public ResourceTransferMessageHandler(Node node) {
		super();
		this.node = node;
	}

	@Override
	public void handle(Message message) {
		ResourceTransferMessagePayload inPay = (ResourceTransferMessagePayload) message.getPayload();
		int cant = inPay.getAmount();
		
		System.out.println("AAAAAAAAA de: "+inPay.getSource()+" para: "+inPay.getDestination());
		
		if (inPay.getDestination().equals(node.getNodeId())) {
			Multiset<Resource> rSelling = ((MarketImpl) node.getMarketManager()
					.market()).getRemoteSelling();
			
			synchronized (rSelling) {
				if (rSelling.count(inPay.getResource()) > 0) {
					rSelling.add(inPay.getResource(), cant);
				}else {
					rSelling.setCount(inPay.getResource(), cant);
				}
				((MarketImpl)node.getMarketManager().market()).interrupt();
			}
		}else if (inPay.getSource().equals(node.getNodeId())) {
			Multiset<ResourceStock> selling = ((MarketImpl) node.getMarketManager()
					.market()).getSelling();
			synchronized (selling) {
				for (ResourceStock r : selling.elementSet()) {
					if (r.resource().equals(inPay.getResource())) {
						int av = selling.count(r);
						
						if (av - cant >= 0) {
							selling.setCount(r, av, av - cant);
							r.remove(cant);
						}
						
					}
				}
			}
			
		}
		

	}

}
